/**
 * Copyright (C), 2020-2021 by colley.ma
 * File Name: ValidationUtils.java
 * Encoding: UTF-8
 * Date: 2021年4月28日 下午3:15:49
 * History:
*/
package com.swak.frame.util;

import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.HibernateValidator;

import com.google.common.collect.Lists;

public class ValidatorUtils {

	/**
	 * 使用hibernate的注解来进行验证
	 */
	private static Validator validator = Validation.byProvider(HibernateValidator.class).configure().failFast(true)
			.buildValidatorFactory().getValidator();

	/**
	 * 注解验证参数
	 * 
	 * @param @param  <T>
	 * @param @param  obj
	 * @param @return
	 * @return String
	 */
	public static <T> String validate(T obj) {
		Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj, Default.class);
		// 检验不合格处理
		if (CollectionUtils.isNotEmpty(constraintViolations)) {
			List<String> tipList = Lists.newArrayList();
			constraintViolations.forEach(constraintViolationImpl -> tipList.add(constraintViolationImpl.getMessage()));
			return StringUtils.join(tipList, ",");
		}
		return null;
	}

	public static Validator getValidator() {
		return validator;
	}
}
